package top.ajunnihao.core.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;
import top.ajunnihao.core.entity.User;
import top.ajunnihao.core.util.resp.JResp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * TODO 用户登录拦截器，拦截所有 u 开头的请求，表示用户登陆后才可以做的操作
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/5/25
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static final String USER = "USER";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(USER);
        if (user == null) {
            // 没有 cookie，进行未登录拦截
            if (uri.endsWith(".do")) {
                // Rest 请求
                // 用户尚未登陆
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JResp.fail("请先登录")));
            } else {
                // MVC 请求
                // 把上一个界面的路径拼接在后面(请求参数也要加上)，用户登陆后跳转到上一个界面，提升用户体验
                String query = request.getQueryString();
                if (StrUtil.isNotBlank(query)) {
                    uri += "?" + query;
                }
                // 重定向
                response.sendRedirect(request.getContextPath() + "/login?ret=" + uri);
            }
            return false;
        }
        // 用户已经登录
        return true;
    }

}
